package com.fly.studio.home.app.config;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.fly.studio.home.app.properties.HomePageThreadPoolProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * 线程池配置
 *
 * @author fuliying3
 * @date 2022/09/02 11:17:00
 */
@Slf4j
@Configuration
public class ThreadPoolConfiguration {

    @Resource
    private HomePageThreadPoolProperties homePageProperties;

    @Bean(value = "homePageThreadPool")
    public ExecutorService homePageThreadPool() {
        BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(homePageProperties.getCapacity());
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(homePageProperties.getThreadName()).build();
        ThreadPoolExecutor.AbortPolicy policy = new ThreadPoolExecutor.AbortPolicy();
        int corePoolSize = homePageProperties.getCorePoolSize();
        int maximumPoolSize = homePageProperties.getMaximumPoolSize();
        long keepAliveTime = homePageProperties.getKeepAliveTime();
        log.info("ThreadPoolConfiguration homePageThreadPool properties -> {}", JSON.toJSONString(homePageProperties));
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, policy);
    }
}
